import { ref, computed } from 'vue'


export function useConversation() {
  const conversationsItems = ref([])
  const activeKey = ref(null)
  const isCreatingNewConversation = computed(() => activeKey.value === null)

  const renameConversation = (key, newName) => {
    const conversation = conversationsItems.value.find((item) => item.key === key)
    if (conversation) {
      conversation.label = newName
    }
  }

  const deleteCon = (key, messagesMap, tempMessages) => {
    const index = conversationsItems.value.findIndex((item) => item.key === key)
    if (index !== -1) {
      conversationsItems.value = conversationsItems.value.filter((item) => item.key !== key)
      // 删除对应的消息列表
      messagesMap.value.delete(key)
      // 如果删除的是当前活动的会话，则切换到第一个会话或null
      if (key === activeKey.value) {
        activeKey.value = conversationsItems.value[0]?.key || null
        tempMessages.value = []
      }
    }
  }

  const addCon = (tempMessages, content) => {
    activeKey.value = null
    tempMessages.value = []
    content.value = ''
  }
  const onConversationClick = (key) => {
    activeKey.value = key
  }
  const selectConversation = (key) => {
    activeKey.value = key
  }

  return {
    conversationsItems,
    activeKey,
    isCreatingNewConversation,
    renameConversation,
    deleteCon,
    addCon,
    onConversationClick,
    selectConversation,
  }
}
